package com.volunteer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.volunteer.common.Result;
import com.volunteer.entity.DemandApplication;
import com.volunteer.entity.ServiceDemand;
import com.volunteer.service.DemandService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 服务需求控制器
 */
@RestController
@RequestMapping("/api/demands")
@RequiredArgsConstructor
public class DemandController {

    private final DemandService demandService;

    /**
     * 分页查询需求列表
     */
    @GetMapping
    public Result<IPage<ServiceDemand>> getDemandList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status) {
        IPage<ServiceDemand> result = demandService.getDemandList(page, size, status);
        return Result.success(result);
    }

    /**
     * 获取需求详情
     */
    @GetMapping("/{id}")
    public Result<ServiceDemand> getDemandById(@PathVariable Long id) {
        ServiceDemand demand = demandService.getDemandById(id);
        return Result.success(demand);
    }

    /**
     * 创建需求（管理员）
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<ServiceDemand> createDemand(@RequestBody ServiceDemand demand) {
        ServiceDemand created = demandService.createDemand(demand);
        return Result.success("创建成功", created);
    }

    /**
     * 更新需求（管理员）
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updateDemand(@PathVariable Long id, @RequestBody ServiceDemand demand) {
        demand.setId(id);
        demandService.updateDemand(demand);
        return Result.success("更新成功", null);
    }

    /**
     * 删除需求（管理员）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteDemand(@PathVariable Long id) {
        demandService.deleteDemand(id);
        return Result.success("删除成功", null);
    }

    /**
     * 申请需求
     */
    @PostMapping("/{id}/apply")
    public Result<Void> applyDemand(
            @PathVariable Long id,
            @RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        String reason = request.getOrDefault("reason", "").toString();
        demandService.applyDemand(id, userId, reason);
        return Result.success("申请成功", null);
    }

    /**
     * 分配需求（管理员）
     */
    @PostMapping("/{id}/assign")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> assignDemand(
            @PathVariable Long id,
            @RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        demandService.assignDemand(id, userId);
        return Result.success("分配成功", null);
    }

    /**
     * 完成需求并结算积分（管理员）
     */
    @PostMapping("/{id}/complete")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> completeDemand(@PathVariable Long id) {
        demandService.completeDemand(id);
        return Result.success("需求已完成，积分已发放", null);
    }

    /**
     * 获取需求的申请列表（管理员）
     */
    @GetMapping("/{id}/applications")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<DemandApplication>> getDemandApplications(@PathVariable Long id) {
        List<DemandApplication> applications = demandService.getDemandApplications(id);
        return Result.success(applications);
    }

    /**
     * 获取用户的申请记录
     */
    @GetMapping("/user/{userId}/applications")
    public Result<List<DemandApplication>> getUserApplications(@PathVariable Long userId) {
        List<DemandApplication> applications = demandService.getUserApplications(userId);
        return Result.success(applications);
    }
}

